//
//  PopupMenuSmallView.swift
//  XMenSwift
//
//  Created by Jason on 2022/4/22.
//

import UIKit

@objc class PopupMenuItemModel: NSObject {
    var title: String = ""
    var titleColor: UIColor?
    var titleFont: Double?
    var rowHeight : CGFloat?
    var image: UIImage?
    
    @objc
    init(title: String, image: UIImage?,titleFont : Double, rowHeight : CGFloat, titleColor : UIColor) {
        self.title = title
        self.image = image
        self.titleColor = titleColor
        self.titleFont = titleFont
        self.rowHeight = rowHeight
    }
}

class PopupMenuSmallViewCell : UITableViewCell {
    
    lazy var imagebtn: UIButton = {
        let btn = UIButton()
//        btn.setImage(UIImage.init(named: "tower_ic_moreAction"), for: .normal)
        btn.isUserInteractionEnabled = false
        return btn
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.font = .systemFont(ofSize: 14)
        label.numberOfLines = 1
        label.text = ""
        return label
    }()
    
    var model : PopupMenuItemModel? {
        didSet {
            titleLabel.textColor = .black
            titleLabel.font = .systemFont(ofSize: 14)

            if let image = model?.image {
                imagebtn.snp.updateConstraints{ make  in
                    make.width.equalTo(44)
                }
                imagebtn.setImage(image, for: .normal)
            } else {
                imagebtn.snp.updateConstraints{ make  in
                    make.width.equalTo(0)
                }
            }
            titleLabel.text = model?.title
            if let color = model?.titleColor {
                titleLabel.textColor = color
            }
            if let font = model?.titleFont {
                titleLabel.font = .systemFont(ofSize: font)
            }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        configUi()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configUi() {
        self.backgroundColor = .clear
        let bgView = UIView();
        bgView.backgroundColor = .clear
        self.contentView.addSubview(bgView)
        bgView.snp.makeConstraints { make  in
            make.edges.equalToSuperview()
        }
        
        bgView.addSubview(imagebtn)
        imagebtn.snp.makeConstraints { make  in
            make.left.equalToSuperview().offset(5)
            make.centerY.equalToSuperview()
            make.width.equalTo(40)
//            make.height.equalTo(40)
        }
        
        bgView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make  in
            make.top.equalToSuperview()
            make.left.equalTo(imagebtn.snp.right)
            make.right.equalToSuperview().offset(10)
            make.bottom.equalToSuperview()
        }

    }
    
}

class PopupMenuSmallView: UIView {
    var tableView : UITableView!
    var didSelectItemBlock:((_ model : PopupMenuItemModel, _ index : Int) -> ())?
    
    @objc
    private(set) weak var bgImageView: UIImageView!
    
    @objc
    var menuItems: [PopupMenuItemModel] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var leftSpacing : CGFloat = 0
    var topSpacing : CGFloat = 0

    //推荐使用此方法初始化 因为有间距的宽高
    @objc class func show(frame: CGRect) -> PopupMenuSmallView {
        //外围间距
        let leftSpa: CGFloat = 10
        let topSpa : CGFloat = 13
        let view =  PopupMenuSmallView.init(frame: CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width + leftSpa, height: frame.size.height + topSpa))
        view.leftSpacing = leftSpa;
        view.topSpacing = topSpa
        view.configUi()
        return view;
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    
    func configUi() {
        let imageView = UIImageView()
        bgImageView = imageView
        self.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        configRightTableView()
        self.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(leftSpacing)
            make.right.equalToSuperview().offset(-leftSpacing)
            make.top.equalToSuperview().offset(topSpacing)
            make.bottom.equalToSuperview().offset(-topSpacing)
        }
    }
    
    func configRightTableView() {
        tableView = UITableView.init(frame: CGRect.zero, style: .grouped)
        if #available(iOS 11.0, *) {
            if (KIsIphoneX) {
                tableView.contentInsetAdjustmentBehavior = .automatic;
            } else {
                tableView.contentInsetAdjustmentBehavior = .never;
            }
        }
        tableView.backgroundColor = .clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none;
        tableView.keyboardDismissMode = .onDrag;
        //是否显⽰示⽔水平滚动条 - NO
        tableView.showsHorizontalScrollIndicator = false;
        //是否显⽰示垂直滚动条- NO
        tableView.showsVerticalScrollIndicator = false;
        //iOS11默认开启为自动模式，这会导致下拉刷新出现问题
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.tableFooterView = UIView();
        tableView.register(PopupMenuSmallViewCell.self, forCellReuseIdentifier: NSStringFromClass(PopupMenuSmallViewCell.self))
        
    }
    
}

//MARK: - UITableViewDelegate UITableViewDataSource
extension PopupMenuSmallView: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuItems.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(PopupMenuSmallViewCell.self), for: indexPath) as? PopupMenuSmallViewCell {
            cell.selectionStyle = .none
            cell.model = menuItems[indexPath.row]
            return cell
        }
        return UITableViewCell();
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = menuItems[indexPath.row]
        if let block = didSelectItemBlock {
            block(model,indexPath.row)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model =  menuItems[indexPath.row]
        return model.rowHeight ?? 44
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    
}
